package com.nl.lib_core.tool.coroutines.extension

import androidx.lifecycle.LifecycleOwner
import com.nl.lib_core.tool.coroutines.LifecycleCoroutineListener
import com.nl.lib_core.tool.coroutines.asyncInBackground
import com.nl.lib_core.tool.coroutines.asyncOnUI
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred

/**
 * 作者: wangfei 创建时间: 2021/12/27 包名: com.nl.lib_core.tool.coroutines.extension 类名: LifecycleExtension
 */
fun <T> CoroutineScope.asyncOnUIWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    block: suspend CoroutineScope.() -> T
): Deferred<T> {
  val deferred = asyncOnUI { block() }
  lifecycleOwner.lifecycle.addObserver(LifecycleCoroutineListener(deferred))
  return deferred
}

fun <T> CoroutineScope.asyncInBgWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    block: suspend CoroutineScope.() -> T
): Deferred<T> {
  val deferred = asyncInBackground { block() }
  lifecycleOwner.lifecycle.addObserver(LifecycleCoroutineListener(deferred))
  return deferred
}

fun <T> CoroutineScope.bindWithLifecycle(
    lifecycleOwner: LifecycleOwner,
    block: CoroutineScope.() -> Deferred<T>
): Deferred<T> {
  val deferred = block.invoke(this)
  lifecycleOwner.lifecycle.addObserver(LifecycleCoroutineListener(deferred))
  return deferred
}
